
local module = _G["BlinkHealthTextModule"]

if select(2, UnitClass("player")) ~= "DRUID" or not module then return end

local tcopy
local ComboSkill = 35
local FinishSkill = 30
local SavageDefenseCost = 60
local config_added = false

local L_SHRED = "칼날 발톱"
local L_SWIFTMEND = "신속한 치유"
local L_LACERATE = "가르기"
local L_LIFEBLOOM = "피어나는 생명"
local L_REJUVENATION = "회복"
local L_REGENERATION = "재생"
local L_STARSURGE = "별폭풍"
local L_SAVAGE_DEFENSE = "야생의 방어"
local L_PREDATORY_SWIFTNESS = "야생의 신속함"
local L_DRUID_CONFIG = "드루이드 설정"
local L_USE_COMBO = "표범의 연계점수, 곰의 |TInterface\\Icons\\Ability_Druid_Lacerate:20|t가르기 수치를 표시합니다."
local L_USE_COMBO_BESIDE_PLAYER = "표범의 연계점수를 플레이어 체력 텍스트 옆에 표시합니다."
local L_USE_COMBO_BESIDE_PLAYER_DESC = "체크하면 표범의 연계점수를 플레이어 체력 텍스트 오른쪽에 표시합니다."
local L_USE_SWIFTMEND = "대상에게 |TInterface\\Icons\\Spell_Nature_Rejuvenation:20|t회복 또는 |TInterface\\Icons\\Spell_Nature_Resistnature:20|t재생이 걸려있을 경우 |TInterface\\Icons\\INV_Relics_IdolofRejuvenation:20|t피어나는 생명 아이콘을 표시합니다."
local L_USE_SAVAGE_DEFENSE = "사용 가능한 |TInterface\\Icons\\Ability_Racial_Cannibalize:20|t야생의 방어 갯수를 표시합니다."
local L_USE_PREDATORY_SWIFTNESS = "|TInterface\\Icons\\Ability_Hunter_Pet_Cat:20|t야생의 신속함 발동시 |TInterface\\Icons\\Spell_Nature_Healingtouch:20|t치유의 손길을 표시합니다."


local defaultDB = {
	db_ver = 1.0,
	use_combo = true,
	use_swiftmend = true,
	use_savage_defense = true,
	use_combo_beside_player = false,
	use_predatory_swiftness = true,
}

module.config = {
	[L_SHRED] = {
		spellid = 5221
	},
	[L_STARSURGE] = {
		spellid = 78674
	},
	[L_SWIFTMEND] = {
		spellid = 18562
	},
	[L_SAVAGE_DEFENSE] = {
		spellid = 62606
	},
	[L_PREDATORY_SWIFTNESS] = {
		spellid = 16974
	},
}

-------------------------------------------------------------------------------
-- local functions
-------------------------------------------------------------------------------

function tcopy(to, from) -- "to" must be a table (possibly empty)
	for k,v in pairs(from) do
		if(type(v)=="table") then
			if not to then to = {} end
			to[k] = {}
			tcopy(to[k], v)
		else
			to[k] = v
		end
	end
end

local function getSize(baseSize, expirationTime, duration)
	local size = (expirationTime-GetTime()) / duration
	if size < 0.3 then
		size = baseSize * .8
	elseif size < 0.6 then
		size = baseSize * 1.0
	else
		size = baseSize * 1.2
	end
	return size / 2
end

local function getComboText()
	local combo = GetComboPoints("player")
	local comboText, r, g, b = "", 1.0, 0.5, 0.1

	if( combo <= 0 )then
		return ""
	end

	if ( UnitPowerType("player") == 3 ) then -- energy
		local mana = UnitMana("player")
		if( mana >= ComboSkill )then
			r = 0.1
			g = 1.0
			b = 0.1 -- green
		elseif( mana >= FinishSkill )then
			r = 0.0
			g = 0.39
			b = 0.88 -- blue
		else
			r = 1.0
			g = 0.1
			b = 0.1 -- red
		end
	end
	return (":|cff%02x%02x%02x%d|r"):format(r * 255, g * 255, b * 255, combo)
end

local function getComboCount()
	for i=1, GetNumShapeshiftForms() do
		local texture, name, isActive, isCastable = GetShapeshiftFormInfo(i)
		if(isActive) then
			if name == "표범 변신" or name == "시르밸라의 발톱" then
				return getComboText()
			elseif name == "곰 변신" then
				return module:getAuraCount("target", L_LACERATE, "HARMFUL")
			end
		end
	end
	return ""
end


-------------------------------------------------------------------------------
-- module functions
-------------------------------------------------------------------------------
function module:init()
	if self.addon.db then
		if not self.addon.db.class or not self.addon.db.class.db_ver or self.addon.db.class.db_ver < defaultDB.db_ver then
			self.addon.db.class = {}
			tcopy(self.addon.db.class, defaultDB)
		end
	end
	self.addon.mainFrame:RegisterEvent("PLAYER_ALIVE")
	self.addon.mainFrame:RegisterEvent("LEARNED_SPELL_IN_TAB")
	self.addon.mainFrame:RegisterEvent("CHARACTER_POINTS_CHANGED")
	self:update()

	if not config_added then
		self:AddMiscConfig{
			type = "description",
			text = L_DRUID_CONFIG,
			fontobject = "QuestTitleFont",
			r = 1,
			g = 0.82,
			b = 0,
			justifyH = "LEFT",
		}
		self:AddMiscConfig{
			type = "toggle",
			text = L_USE_COMBO,
			tooltip = L_USE_COMBO,
			get = function ()
				if self.addon and self.addon.db then
					return self.addon.db.class.use_combo
				end
				return
			end,
			set = function (value)
				self.addon.db.class.use_combo = value
			end,
			needRefresh = true,
		}
		self:AddMiscConfig{
			type = "toggle",
			depth = 1,
			text = L_USE_COMBO_BESIDE_PLAYER,
			tooltip = L_USE_COMBO_BESIDE_PLAYER_DESC,
			get = function ()
				if self.addon and self.addon.db then
					return self.addon.db.class.use_combo_beside_player
				end
				return
			end,
			set = function (value)
				self.addon.db.class.use_combo_beside_player = value
			end,
			disable = function ()
				return not self.addon.db.class.use_combo
			end,
			needRefresh = true,
		}
		self:AddMiscConfig{
			type = "toggle",
			text = L_USE_PREDATORY_SWIFTNESS,
			tooltip = L_USE_PREDATORY_SWIFTNESS,
			get = function ()
				if self.addon and self.addon.db then
					return self.addon.db.class.use_predatory_swiftness
				end
				return
			end,
			set = function (value)
				self.addon.db.class.use_predatory_swiftness = value
			end,
		}
		self:AddMiscConfig{
			type = "toggle",
			text = L_USE_SAVAGE_DEFENSE,
			tooltip = L_USE_SAVAGE_DEFENSE,
			get = function ()
				if self.addon and self.addon.db then
					return self.addon.db.class.use_savage_defense
				end
				return
			end,
			set = function (value)
				self.addon.db.class.use_savage_defense = value
			end,
		}
		self:AddMiscConfig{
			type = "toggle",
			text = L_USE_SWIFTMEND,
			tooltip = L_USE_SWIFTMEND,
			get = function ()
				if self.addon and self.addon.db then
					return self.addon.db.class.use_swiftmend
				end
			end,
			set = function (value)
				self.addon.db.class.use_swiftmend = value
			end,
		}
		config_added = true
	end
end

function module:update()
	self.primary = GetSpecialization()
	for auraName, t in pairs(self.config) do
		if t.talent and t.talent > 0 then
			local name, iconTexture, tier, column, selected, available = GetTalentInfo(t.talent);
			if name and available then
				self.config[auraName].use = true
				if t.event and self.addon and self.addon.mainFrame then
					self.addon.mainFrame:RegisterEvent(t.event)
				end
			end
		else
			self.config[auraName].use = false
			if IsPlayerSpell(t.spellid) then
				self.config[auraName].use = true
				if t.event and self.addon and self.addon.mainFrame then
					self.addon.mainFrame:RegisterEvent(t.event)
				end
			end
		end
	end

	ComboSkill = 40
--	if self.primary == 1 then -- 조화
--		self.config[L_STARSURGE].use = true
--	elseif self.primary == 2 then -- 야성
--		self.config[L_MANGLE_CAT].use = true
--	elseif self.primary == 3 then -- 수호
--		self.config[L_MANGLE_BEAR].use = true
--	elseif self.primary == 4 then -- 회복
--		self.config[L_SWIFTMEND].use = true
--	end

--	if self.config[L_MANGLE_CAT].use then
--		_, _, _, ComboSkill = GetSpellInfo(33876) -- Mangle for CAT
--	end
	if self.config[L_SAVAGE_DEFENSE].use then
		_, _, _, SavageDefenseCost = GetSpellInfo(self.config[L_SAVAGE_DEFENSE].spellid) -- L_SAVAGE_DEFENSE
	end
end

function module:LEARNED_SPELL_IN_TAB(...)
	self:update()
end
module.CHARACTER_POINTS_CHANGED = module.LEARNED_SPELL_IN_TAB
function module:PLAYER_ALIVE(...)
	self.addon.mainFrame:UnregisterEvent("PLAYER_ALIVE")
	self:update()
end

function module:getSavageDefenseText()
	local r, g, b = 1.0, 0.5, 0.1
	if self.config[L_SAVAGE_DEFENSE].use then
		if ( UnitPowerType("player") == 1 ) then -- rage
			local charges = GetSpellCharges(self.config[L_SAVAGE_DEFENSE].spellid)
			if charges > 0 then
				local mana = UnitMana("player")
				if( mana >= SavageDefenseCost )then
					r = 0.1
					g = 1.0
					b = 0.1 -- green
				else
					r = 1.0
					g = 0.1
					b = 0.1 -- red
				end
				return (":|cff%02x%02x%02x%d|r"):format(r * 255, g * 255, b * 255, charges)
			end
		end
	end
	return ""
end

function module:getPlayerText()
	local text = ""
	local aura, rank, icon, count, debufType, duration, expirationTime
	local size = self.addon.db.fontSizeHealth

	if self.config[L_PREDATORY_SWIFTNESS].use and self.addon.db.class.use_predatory_swiftness then
		aura, rank, icon, count, debufType, duration, expirationTime = UnitAura("player", L_PREDATORY_SWIFTNESS, nil, "HELPFUL")
		if aura then
			size = getSize(self.addon.db.fontSizeHealth, expirationTime, duration)
			text = text .. (":|TInterface\\Icons\\Spell_Nature_Healingtouch:%d|t"):format(size)
		end
	end

	if self.addon.db.class.use_combo and self.addon.db.class.use_combo_beside_player then
		text = text .. getComboCount()
	end

	if self.config[L_SAVAGE_DEFENSE].use and self.addon.db.class.use_savage_defense then
		text = text .. self:getSavageDefenseText()
		aura, rank, icon, count, debufType, duration, expirationTime = UnitAura("player", L_SAVAGE_DEFENSE, nil, "HELPFUL")
		if aura then
			size = getSize(self.addon.db.fontSizeHealth, expirationTime, duration)
			text = text .. (":|T%s:%d|t"):format(icon, size)
		end
		return text
	end
	return text
end

function module:getTargetText()
	local text = ""
	local m_cat, m_bear, aura, rank, icon, count, debufType, duration, expirationTime
	local size

	if self.addon.db.class.use_combo and not self.addon.db.class.use_combo_beside_player then
		text = getComboCount()
	end

	if self.config[L_SWIFTMEND].use and self.addon.db.class.use_swiftmend then
		aura, rank, icon, count, debufType, duration, expirationTime = UnitAura("target", L_REJUVENATION, nil, "HELPFUL")
		if aura then
			size = getSize(self.addon.db.fontSizeHealth, expirationTime, duration)
			text = text .. (":|TInterface\\Icons\\INV_Relics_IdolofRejuvenation:%d|t"):format(size)
		end
		aura, rank, icon, count, debufType, duration, expirationTime = UnitAura("target", L_REGENERATION, nil, "HELPFUL")
		if aura then
			size = getSize(self.addon.db.fontSizeHealth, expirationTime, duration)
			text = text .. (":|TInterface\\Icons\\INV_Relics_IdolofRejuvenation:%d|t"):format(size)
		end
	end

	return text
end

